package PDFinfo;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecFactory;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.params.HttpParams;
import org.pdfbox.cos.COSDocument;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;

public class PDF {

	public static void main(String[] args) {
		connect("");
	}

	public static void connect(String paperLink) {
		URL url1 = null;
		String ref = "";
		try { // http://www.gnostice.com/nl_article.asp?id=207&t=How_To_Read_A_PDF_File_From_A_URL_In_Java
			url1 = new URL(
					"http://ieeexplore.ieee.org.ezproxy.lib.ucalgary.ca/stamp/stamp.jsp?tp=&arnumber=1532628");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			// Contacting the URL
			System.out.print("Connecting to " + url1.toString() + " ... \n");
			URLConnection urlConn = null;
			try {
				urlConn = url1.openConnection();
			} catch (IOException e) {
				System.out.println("ERRRORRR connecting");
				e.printStackTrace();
			}
			try {
				int byteC = urlConn.getInputStream().read();
				while (byteC != -1) {
					ref += (char) byteC;
					byteC = urlConn.getInputStream().read();
				}
				ref = ref.split("\"")[1];
				System.out.println("\nREF IS: " + ref);
				getPdfContents(ref);

			} catch (IOException e1) {
				System.out.println("ERRRORRR reading");
				e1.printStackTrace();
			}
		} catch (NullPointerException npe) {
			System.out.println("FAILED.\n[" + npe.getMessage() + "]\n");
		}
	}

	public static void getPdfContents(String url) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope("136.159.235.223", 8080),
					new UsernamePasswordCredentials("marusso", "Orlando1"));

			// THIS IS HOW URL LOOK LIKE
			// http://ieeexplore.ieee.org.ezproxy.lib.ucalgary.ca/stamp/stamp.jsp?tp=&arnumber=1532628
			// REMOVE FIRST 7 symbols

			HttpHost targetHost = new HttpHost(
					"ieeexplore.ieee.org.ezproxy.lib.ucalgary.ca/stamp/stamp.jsp?tp=&arnumber=1532628"); // url.substring(7));
																											// ref.substring(7)
			HttpHost proxy = new HttpHost("193.140.109.10", 8080); // ieee host

			httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					proxy);

			HttpGet httpget = new HttpGet("/");
			System.out.println("----------------------------------------");
			System.out.println("Content request is " + httpget.getRequestLine()
					+ " via " + proxy);
			System.out.println("Target: " + targetHost);

			// Create a local instance of cookie store
			CookieStore cookieStore = new BasicCookieStore();

			// Bind custom cookie store to the local context
			httpclient.setCookieStore(cookieStore);
			CookieSpecFactory csf = new CookieSpecFactory() {
				@Override
				public CookieSpec newInstance(HttpParams params) {
					return new BrowserCompatSpec() {
						@Override
						public void validate(Cookie cookie, CookieOrigin origin)
								throws MalformedCookieException {
							System.out.println("Pushed Cookie :" + cookie);
						}
					};
				}
			};

			System.out.println("Push EmAll");

			httpclient.getCookieSpecs().register("easy", csf);
			httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
					"easy");

			// NOT DOING ANYTHING AFTER THIS
			HttpResponse response = httpclient.execute(targetHost, httpget);
			System.out.println("HELLOOOOOOOOOOOOOOOOOOOO RESPONCE"); // RIGHT
																		// HERE
																		// WONT
																		// PRINT

			HttpEntity entity = response.getEntity();
			System.out.println("BYEEEEEEEEEE at entity");

			System.out.println("Hurray! " + response.getStatusLine());

			System.out.println("PDF Size: " + entity.getContentLength()
					+ " bytes");
			PDFParser parser = new PDFParser(entity.getContent());
			System.out.println("Downloading & Parsing PDF");
			parser.parse();
			System.out.println("Downloaded & Parsed Successfully");
			COSDocument cosDoc = parser.getDocument();
			PDFTextStripper pdfStripper = new PDFTextStripper();
			PDDocument pdDoc = new PDDocument(cosDoc);
			pdfStripper.setStartPage(1);
			pdfStripper.setEndPage(1);
			pdfStripper.setLineSeparator(" ");
			pdfStripper.setPageSeparator(" ");
			String parsedText = pdfStripper.getText(pdDoc);
			System.out.println("Getting ID Area of PDF");
			// parsedText = parsedText.substring((parsedText.indexOf(starter) +
			// starter.length())/**, parsedText.indexOf("Abstract")**/);
			if (parsedText.indexOf("Abstract—") > 0) {
				parsedText = parsedText.substring(0,
						parsedText.indexOf("Abstract—"));
			}
			cosDoc.close();
			pdDoc.close();
			System.out.println("Manipulating ID Area");
			parsedText = parsedText.trim().replaceAll(" +", " ");
			parsedText = parsedText.trim();

			System.out.println("\nID Area");
			System.out.println(parsedText);

			// LinkedList tempEmails=getEmail(parsedText);
			//
			// for(String s:getCombinedEmails(parsedText)){
			// tempEmails.add(s);
			// }
			//
			// System.out.println("");
			// if(tempEmails.size()>0){
			// emails.add(tempEmails);
			// }else{
			// LinkedList nullList = new LinkedList();
			// nullList.add("no@nomail.com");
			// emails.add(nullList);
			// }
			// //String tempAddress =
			// getAddress(parsedText,Main.getG().authors.get(i),tempEmails).trim().replaceAll(" +",
			// " ");
			// //tempAddress=tempAddress.trim();
			// matchEmAll(Main.getG().authors.get(i),tempEmails,i);
			// System.out.println("--------------------------------------------------------");
			// EntityUtils.consume(entity);
		} catch (Exception e) {

		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
	}
}
